package tt.dz.egobus.servicemanager.business.task.job;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import tt.dz.egobus.base.context.SpringApplicationHolder;

import java.util.Map;

/**
 * @author Anson
 * @date 17-8-9
 * @name 计划任务抽象层开始
 * @since 1.0.6
 */
public abstract class AbstractQuartzDynamicTask implements QuartzDynamicTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractQuartzDynamicTask.class);

    protected static final String JOB_EXECUTION_CONTEXT_KEY = JobExecutionContext.class.getName();

    /**
     * @author Anson
     * @date 17-8-9
     * @name 判断当前是否初始化
     * @since 1.0.6
     */
    protected abstract boolean isInit(Map<String,Object> jobDatamap);

    /**
     * @author Anson
     * @date 17-8-9
     * @name 判断 当前是否超时
     * @since 1.0.6
     */
    protected abstract boolean isTimeout(Map<String,Object> jobDatamap);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LOGGER.info("计划任务开始->jobKey={},triggerKey={}",
                context.getTrigger().getJobKey().getName(),
                context.getTrigger().getKey().getName());
        Map<String, Object> jobDatamap = context.getMergedJobDataMap();
        jobDatamap.putIfAbsent(JOB_EXECUTION_CONTEXT_KEY, context);
        if (this.isInit(jobDatamap)) {
            this.init(jobDatamap);
        }
        if (this.isTimeout(jobDatamap)) {
            this.timeout(jobDatamap);
        }
    }


    @Override
    public void init(Map<String,Object> jobDatamap) {
        // 挂钩
    }

    @Override
    public void timeout(Map<String,Object> jobDatamap) {
        // 挂钩
    }

    /**
     * 运行中Application是存在并且已经实例化了的
     *
     * @return
     */
    protected ApplicationContext getSpringContext() {
        return SpringApplicationHolder.getApplicationContext();
    }

    /**
     * @param jobDatamap 当前既定任务的参数map
     * @author Anson
     * @date 17-8-10
     * @name 获取任务执行的环境变量
     * @since 1.0.6
     */
    protected JobExecutionContext getJobExecutionContext(Map<String, Object> jobDatamap) {
        Object obj = jobDatamap.get(JOB_EXECUTION_CONTEXT_KEY);
        if (obj == null || JobExecutionContext.class.isAssignableFrom(obj.getClass())) {
            return (JobExecutionContext) obj;
        }
        return null;
    }
}
